package com.example.propertymanagement.service;

import com.example.propertymanagement.dto.CommunityDTO;
import com.example.propertymanagement.entity.Community;
import com.example.propertymanagement.repository.CommunityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * CommunityService：用于处理与小区相关的业务逻辑
 */
@Service
public class CommunityService {

    @Autowired
    private CommunityRepository communityRepository; // 注入 CommunityRepository

    /**
     * 获取所有小区信息
     * @return 返回小区列表DTO
     */
    public List<CommunityDTO> getAllCommunities() {
        List<Community> communities = communityRepository.findAll(); // 获取所有小区信息
        return communities.stream() // 使用 Java 8 的流式处理
                .map(this::convertToDTO) // 将实体类转换为 DTO
                .collect(Collectors.toList()); // 收集成 List
    }

    /**
     * 根据小区ID获取小区信息
     * @param id 小区ID
     * @return 返回小区DTO
     */
    public Optional<CommunityDTO> getCommunityById(Integer id) {
        Optional<Community> communityOptional = communityRepository.findById(id);
        return communityOptional.map(this::convertToDTO);  // 转换为 DTO
    }

    /**
     * 根据小区编号查询小区信息
     * @param communityCode 小区编号
     * @return 返回小区DTO
     */
    public Optional<CommunityDTO> getCommunityByCode(String communityCode) {
        Optional<Community> communityOptional = communityRepository.findByCommunityCode(communityCode);
        return communityOptional.map(this::convertToDTO);  // 转换为 DTO
    }

    /**
     * 添加新的小区
     * @param communityDTO 小区DTO
     * @return 返回新增的小区DTO
     */
    public CommunityDTO createCommunity(CommunityDTO communityDTO) {
        Community community = new Community();
        community.setCommunityCode(communityDTO.getCommunityCode());
        community.setCommunityName(communityDTO.getCommunityName());
        community.setAddress(communityDTO.getAddress());
        community.setArea(communityDTO.getArea());
        community.setTotalBuildings(communityDTO.getTotalBuildings());
        community.setTotalHouseholds(communityDTO.getTotalHouseholds());
        community.setGreeningRate(communityDTO.getGreeningRate());
        community.setThumbnail(communityDTO.getThumbnail());
        community.setDeveloper(communityDTO.getDeveloper());
        community.setCreateTime(new Date());  // 设置当前时间
        community.setStatus(communityDTO.getStatus());

        // 保存小区
        Community savedCommunity = communityRepository.save(community);
        return convertToDTO(savedCommunity);  // 返回保存后的小区DTO
    }

    /**
     * 更新小区信息
     * @param id 小区ID
     * @param communityDTO 小区DTO
     * @return 更新后的小区DTO
     */
    public CommunityDTO updateCommunity(Integer id, CommunityDTO communityDTO) {
        Optional<Community> existingCommunityOptional = communityRepository.findById(id);
        if (existingCommunityOptional.isPresent()) {
            Community existingCommunity = existingCommunityOptional.get();
            existingCommunity.setCommunityCode(communityDTO.getCommunityCode());
            existingCommunity.setCommunityName(communityDTO.getCommunityName());
            existingCommunity.setAddress(communityDTO.getAddress());
            existingCommunity.setArea(communityDTO.getArea());
            existingCommunity.setTotalBuildings(communityDTO.getTotalBuildings());
            existingCommunity.setTotalHouseholds(communityDTO.getTotalHouseholds());
            existingCommunity.setGreeningRate(communityDTO.getGreeningRate());
            existingCommunity.setThumbnail(communityDTO.getThumbnail());
            existingCommunity.setDeveloper(communityDTO.getDeveloper());
            existingCommunity.setStatus(communityDTO.getStatus());

            // 更新小区
            Community updatedCommunity = communityRepository.save(existingCommunity);
            return convertToDTO(updatedCommunity);  // 返回更新后的小区DTO
        } else {
            throw new RuntimeException("小区ID " + id + " 不存在！");
        }
    }

    /**
     * 删除小区
     * @param id 小区ID
     */
    public void deleteCommunity(Integer id) {
        Optional<Community> communityOptional = communityRepository.findById(id);
        if (communityOptional.isPresent()) {
            communityRepository.deleteById(id);  // 删除小区
        } else {
            throw new RuntimeException("小区ID " + id + " 不存在！");
        }
    }

    /**
     * 将 Community 实体转换为 CommunityDTO
     * @param community Community 实体
     * @return 返回转换后的 CommunityDTO
     */
    private CommunityDTO convertToDTO(Community community) {
        CommunityDTO dto = new CommunityDTO();
        dto.setId(community.getId());
        dto.setCommunityCode(community.getCommunityCode());
        dto.setCommunityName(community.getCommunityName());
        dto.setAddress(community.getAddress());
        dto.setArea(community.getArea());
        dto.setTotalBuildings(community.getTotalBuildings());
        dto.setTotalHouseholds(community.getTotalHouseholds());
        dto.setGreeningRate(community.getGreeningRate());
        dto.setThumbnail(community.getThumbnail());
        dto.setDeveloper(community.getDeveloper());
        dto.setCreateTime(community.getCreateTime());
        dto.setStatus(community.getStatus());  // 设置枚举和状态标签

        // 假设只取第一个管理员名字
        if (community.getAdmins() != null && !community.getAdmins().isEmpty()) {
            dto.setAdminIds(community.getAdmins().stream()
                    .map(admin -> admin.getId())
                    .collect(Collectors.toList()));
        }

        // 假设只取楼栋 ID 列表
        if (community.getBuildings() != null && !community.getBuildings().isEmpty()) {
            dto.setBuildingIds(community.getBuildings().stream()
                    .map(building -> building.getId())
                    .collect(Collectors.toList()));
        }

        return dto;
    }
}